<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model.trim="name" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.trim="age" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="save">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="list.splice(index, 1)">删除</button>
            <button @click="doEdit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        { name: "jack", age: 99, gender: "男" },
        { name: "rose", age: 43, gender: "女" },
        { name: "andy", age: 99, gender: "男" },
      ],
      name: "",
      age: "",
      gender: "",
    //   isAdd: true,
      idx: -1,
    };
  },

  methods: {
    save() {
      // 非空判断
      if (this.name == "" || this.age == "" || this.gender == "")
        return alert("请输入完整内容");

      if (this.idx == -1) {
        // 添加
        this.list.push({
          name: this.name,
          age: this.age,
          gender: this.gender,
        });
      } else {
        // 做修改的事
        this.list[this.idx].name = this.name;
        this.list[this.idx].age = this.age;
        this.list[this.idx].gender = this.gender;

        // this.$set(this.list, this.idx,  { name: this.name, age: this.age, gender: this.gender } )
        // 代表下次默认是添加
        // this.isAdd = true;
        this.idx = -1
      }

      // 清空输入内容
      this.name = this.age = this.gender = "";
    },

    // 编辑的点击事件
    doEdit(index) {
      // 被点的下标存起来
      this.idx = index;
      this.isAdd = false;
      // 根据下标拿到数据，赋值给页面
      this.name = this.list[index].name;
      this.age = this.list[index].age;
      this.gender = this.list[index].gender;
    },
  },
};
</script>